<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>二级联动-版本2</title>

</head>
<body>
城市: <select id="sltCity"></select>
学校：<select id="sltSchool"></select>
</body>
<script src="mock/cities.js"></script>
<script>

    /**
     *  不要重复制造轮子
     *    封装成
     *      函数 ---复用
     * */

    window.onload = function () {

        var sltCity = document.getElementById('sltCity');

        initSelect('sltCity', cities);

        sltCity.onchange = sltCityChange;

    }

    function sltCityChange() {

        var selectedValue = this.selectedOptions[0].value;

        var currentCity = cities.find(function (city) {
            return city.id == selectedValue;
        });

        initSelect('sltSchool', currentCity.schools);

    }



    function initSelect(selector, arr) {
        var slt = document.getElementById(selector);

        slt.innerHTML = '';

        for (var i = 0; i < cities.length; i++) {

            var opt = document.createElement('option');
            opt.value = arr[i].id;
            opt.text = arr[i].name;

            slt.append(opt);
        }
    }


</script>

</html>